/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ListagemCondominios.java
 *
 * Created on Jun 1, 2010, 1:34:17 PM
 */
package adcon.apresentacao;

import adcon.negocio.condominio.Condominio;
import adcon.persistencia.DAO;
import avant.view.AvantViewUtil;
import avant.view.model.AvantTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDesktopPane;

/**
 *
 * @author Administrador
 */
public class TelaListagemCondominios extends javax.swing.JInternalFrame {

    private AvantTableModel<Condominio> modeloTabelaCondominio;
    JDesktopPane desktop;
    List<Condominio> condominios;
    TelaCadastroCondominios tela;

    /** Creates new form ListagemCondominios */
    public TelaListagemCondominios(JDesktopPane desktop) throws Exception {
        this.desktop = desktop;
        initComponents();
        carregarTabelaCondominio();
        adicionarOuvintes();
    }

    private List carregarTabela() {

        try {
            condominios = new DAO().listar(Condominio.class, "CondominioPorAtivo", true);
            return condominios;
        } catch (Exception e) {
            e.printStackTrace();
            AvantViewUtil.exibirErro("Não foi possível comunicar com o Banco de Dados!", this);
            return condominios;
        }
    }

    private void carregarAtivos() {

        condominios = carregarTabela();
        modeloTabelaCondominio.setObjetos(condominios);

    }

    private void carregarInativos() {

        try {
            condominios = new DAO().listar(Condominio.class, "CondominioPorAtivo", false);
            modeloTabelaCondominio.setObjetos(condominios);
        } catch (Exception e) {
            e.printStackTrace();
            AvantViewUtil.exibirErro("Não foi possível comunicar com o Banco de Dados!", this);
        }
    }

    private void cancelar(){
        dispose();
    }

    private void editar() {
        if (tbCondominios.getSelectedRow() >= 0) {
            Condominio condominio = modeloTabelaCondominio.getObjetoSelecionado();
            verificarJanelaAberta(condominio);
        } else {
            AvantViewUtil.exibirAdvertencia("Você deve selecionar um registro antes de editar!", this);
        }
    }

    private void adicionar() {
        Condominio condominio = new Condominio();
        verificarJanelaAberta(condominio);
    }

    private void verificarJanelaAberta(Condominio condominio) {

        if (desktop.getIndexOf(tela) == -1) {
            try {
                tela = new TelaCadastroCondominios(condominio, modeloTabelaCondominio);
            } catch (Exception ex) {
                ex.printStackTrace();
                AvantViewUtil.exibirErro("Não foi possível se comunicar com o Banco de dados!", this);
            }
            desktop.add(tela);
            Principal.centralizar(tela);
            tela.setVisible(true);
        } else {
            try {
                tela.setSelected(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void adicionarOuvintes() {
        ControladorDeEventos controlador = new ControladorDeEventos();

        btnAdicionar.addActionListener(controlador);
        btnEditar.addActionListener(controlador);

        txtPesquisar.addKeyListener(new KeyAdapter() {

            @Override
            public void keyTyped(KeyEvent evt) {
                pesquisar();
            }
        });
        tbCondominios.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getSource() == tbCondominios && e.getClickCount() == 2) {
                    editar();
                }
            }
        });

        checkBoxInativo.addActionListener(controlador);

        tbCondominios.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                    editar();
                }
            }
        });
    }

    private void pesquisar() {
        modeloTabelaCondominio.filtrar();

    }

    private void carregarTabelaCondominio() {
        modeloTabelaCondominio = new AvantTableModel<Condominio>(tbCondominios, carregarTabela(), new String[]{"Nome", "CNPJ", "Rua", "Número", "Bairro", "Contato"}) {

            @Override
            public Object getValor(Condominio objeto, int indiceColuna) {
                switch (indiceColuna) {
                    case 0:
                        return objeto.getRazaoSocial();
                    case 1:
                        return objeto.getCnpj();
                    case 2:
                        return objeto.getEndereco().getRua();
                    case 3:
                        return objeto.getEndereco().getNumero();
                    case 4:
                        return objeto.getEndereco().getBairro();
                    case 5:
                        return objeto.getContato();
                    default:
                        throw new RuntimeException("Não foi possível definir o campo do Condominio");
                }
            }

            @Override
            protected List<Condominio> getFiltrar(List<Condominio> condominios) {
                List<Condominio> listaFiltrada = new ArrayList<Condominio>();
                for (Condominio condominio : condominios) {
                    if (condominio.getRazaoSocial().toLowerCase().contains(txtPesquisar.getText()) && !checkBoxInativo.isSelected()) {
                        listaFiltrada.add(condominio);
                        System.out.println("fasdfsdsa");
                    }
                    if (condominio.getRazaoSocial().toLowerCase().contains(txtPesquisar.getText()) && checkBoxInativo.isSelected()) {
                        listaFiltrada.add(condominio);
                        System.out.println("poootz");
                    }
                }
                if (listaFiltrada.size() > 0) {
                    return listaFiltrada;
                } else {
                    return condominios;
                }
            }
        };

        tbCondominios.setAutoResizeMode(0);
        modeloTabelaCondominio.setLargura(0, -1, 300, 300);
        modeloTabelaCondominio.setLargura(1, -1, 200, 300);
        modeloTabelaCondominio.setLargura(2, -1, 300, 300);
        modeloTabelaCondominio.setLargura(4, -1, 200, 300);
        modeloTabelaCondominio.setLargura(5, -1, 300, 300);
    }

    private class ControladorDeEventos implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == btnAdicionar) {
                adicionar();
            }else if (e.getSource() == btnEditar) {
                editar();
            } else if (e.getSource() == checkBoxInativo) {
                if (checkBoxInativo.isSelected()) {
                    carregarInativos();
                } else {
                    carregarAtivos();
                }
            }else if(e.getSource() == btnCancelar){
                 cancelar();
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtPesquisar = new javax.swing.JTextField();
        checkBoxInativo = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbCondominios = new javax.swing.JTable();
        jPanel9 = new javax.swing.JPanel();
        btnAdicionar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Listagem de Condominios");
        setNextFocusableComponent(txtPesquisar);
        setPreferredSize(new java.awt.Dimension(724, 502));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(51, 51, 51), 1, true), "Buscar", javax.swing.border.TitledBorder.RIGHT, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        txtPesquisar.setToolTipText("Digite o que deseja Pesquisar");

        checkBoxInativo.setText("Inativo?");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtPesquisar, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(checkBoxInativo)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(checkBoxInativo))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tbCondominios.setFont(new java.awt.Font("Lucida Sans", 0, 12));
        tbCondominios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbCondominios.setNextFocusableComponent(btnAdicionar);
        jScrollPane1.setViewportView(tbCondominios);

        btnAdicionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adcon/imagens/salvar.png"))); // NOI18N
        btnAdicionar.setText("Adicionar");
        btnAdicionar.setToolTipText("Adicionar um novo Condomínio");

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adcon/imagens/editar.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.setToolTipText("Editar um Condomínio");

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adcon/imagens/cancelar.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setToolTipText("Adicionar um novo Condomínio");

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGap(131, 131, 131)
                .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(150, Short.MAX_VALUE))
        );

        jPanel9Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdicionar, btnEditar});

        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdicionar)
                    .addComponent(btnEditar)
                    .addComponent(btnCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 698, Short.MAX_VALUE)
                    .addComponent(jPanel9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(16, 16, 16))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JCheckBox checkBoxInativo;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbCondominios;
    private javax.swing.JTextField txtPesquisar;
    // End of variables declaration//GEN-END:variables
}
